package main

import . "local/algorithm/util"

func reverseKGroup(head *ListNode, k int) *ListNode {
	node := head
	for i := 0; i < k; i++ {
		if node == nil {
			return head
		}
		node = node.Next
	}

	newhead := revert(head, node)
	head.Next = reverseKGroup(node, k)
	return newhead
}

func revert(first, last *ListNode) *ListNode {
	prev := last
	current := first
	for current != last {
		tmp := current.Next
		current.Next = prev
		prev = current
		current = tmp
	}

	return prev
}

func main() {
	list := GenerateLinkedList([]int{1, 2, 3, 4, 5})
	newList := reverseKGroup(list, 2)
	PrintLinkedList(newList)
}
